#include "../lib_include/EventLoopThread.h"
#include "../lib_include/EventLoop.h"

using namespace netlib;
using namespace netlib::net;

EventLoopThread::EventLoopThread(const ThreadInitCallback& cb, const string& name)
  : loop_(NULL),
    exiting_(false),
    thread_(std::bind(&EventLoopThread::threadFunc, this), name),
    mutex_(),
    cond_(mutex_),
    callback_(cb)
{ }

EventLoopThread::~EventLoopThread()
{
    exiting_ = true; // 设置退出标志
    if (loop_ != NULL)
    {
        loop_->quit(); // 退出IO线程
        thread_.join();
    }
}

EventLoop* EventLoopThread::startLoop()
{
    assert(!thread_.started());
    thread_.start();

    EventLoop* loop = NULL;
    {
        MutexLockGuard lock(mutex_);
        while (loop_ == NULL) // 等待IO线程的EventLoop创建完成
            cond_.wait();
        loop = loop_;
    }
    return loop;
}

void EventLoopThread::threadFunc()
{
    EventLoop loop; // 栈上的对象，函数退出自动销毁，loop_失效了，同时创建的IO线程也退出了

    if (callback_)
        callback_(&loop);

    {
        MutexLockGuard lock(mutex_);
        loop_ = &loop;
        cond_.notify(); // IO线程创建完EventLoop对象，唤醒主线程
    }

    loop.loop();
    MutexLockGuard lock(mutex_);
    loop_ = NULL;
}

